package com.itheima.reggie.web.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.entity.dto.LoginFrontDTO;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ThreadLocalUtil;
import com.itheima.reggie.utils.ValidateCodeUtils;
import com.itheima.reggie.web.R;
import com.itheima.reggie.web.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

import static com.itheima.reggie.utils.RedisConstant.FRONT_USER_LOGIN_CODE;
import static com.itheima.reggie.utils.RedisConstant.FRONT_USER_LOGIN_TTL;

/**
 * 用户控制器
 *
 * @Name : UserController
 * @Author : WuQiang
 * @Date : 2022-08-19 15:22
 * @Description : 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

  /*  @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody LoginFrontDTO dto, HttpSession session) {
        //随机获取6位验证码
        String code = ValidateCodeUtils.generateCode(6);
        log.info("手机号:{},随机验证码：{}", dto.getPhone(), code);
        //把验证码保存到session中
        session.setAttribute("login_code", code);
        return R.success("验证码发送成功", code);
    }*/
  @PostMapping("/sendMsg")
  public R sendMsg(@RequestBody LoginFrontDTO dto) {
      //随机获取6位验证码
      String code = ValidateCodeUtils.generateCode(6);
      log.info("手机号:{},随机验证码：{}", dto.getPhone(), code);
      //把验证码保存到redis中
      String key = FRONT_USER_LOGIN_CODE + dto.getPhone();
      stringRedisTemplate.opsForValue().set(key,code,FRONT_USER_LOGIN_TTL, TimeUnit.SECONDS);
      return R.success("验证码发送成功", code);
  }

    /**
     * 手机验证码登录
     *
     * @param dto
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginFrontDTO dto, HttpSession session) {
        //获取前端输入的验证码
        String inputCode = dto.getCode();
        String phone = dto.getPhone();
        if (StringUtils.isBlank(inputCode)) {
            throw new BusinessException("验证码不能为空");
        }

        //获取redis中的验证码
        String key = FRONT_USER_LOGIN_CODE + phone;
        String redisCode = stringRedisTemplate.opsForValue().get(key);
        if (!inputCode.trim().equals(redisCode)) {
            throw new BusinessException("验证码有误，请重新输入!");
        }

        //将redis中的验证码清空
       stringRedisTemplate.delete(key);
        //根据用户输入手机号，去数据库查询
        User user = userService.getOne(Wrappers.lambdaQuery(User.class)
                .eq(StringUtils.isNotBlank(phone), User::getPhone, phone));
        if (user == null) {
            //用户不存在
            //去注册
            user = new User();
            user.setName("user_" + phone);
            user.setStatus(1);
            user.setPhone(phone);
            userService.save(user);
        }
        //将用户信息存入session
        session.setAttribute("userId", user.getId());
        //返回前端
        return R.success("登录成功", user);
    }


    /**
     * 前台用户登出
     *
     * @return
     */
    @PostMapping("/loginout")
    public R loginout() {
        ThreadLocalUtil.removeCurrentId();
        return R.success("退出登录成功");
    }
}
